package com.geek.javase.ch17.work.tcpwork.tcp07v2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @Desc TODO
 * @Author
 * @Date 2025/11/10
 */
public class TCPServer {

    //线程池
    private static final ThreadPool pool = new ThreadPool(ThreadPoolConfig.CORE_POOL_SIZE , ThreadPoolConfig.MAX_POOL_SIZE , ThreadPoolConfig.QUEUE_SIZE);
    //线程池最大执行的任务数
    private static final int MAX_CLIENTS = ThreadPoolConfig.MAX_POOL_SIZE + ThreadPoolConfig.QUEUE_SIZE;


    public static void main(String[] args) {
        System.out.println("------------- 服务端 ------------");
        //存储接入的客户端
        CopyOnWriteArrayList<Socket> clients = new CopyOnWriteArrayList<>();

        ServerSocket ss = null;
        try {
            ss = new ServerSocket(8899);

            //无限接入客户端
            while (true){
                Socket socket = ss.accept();
                clients.add(socket);

                //为每一个接入的客户端，分配一个话务员执行转发消息的任务
                pool.execute(new ServerTasker(socket , clients , Thread.currentThread()));
                System.out.println(socket.getRemoteSocketAddress()+" 客户端上线~");

                //达到能够接纳最大线程数
                if(clients.size() == MAX_CLIENTS){
                    ss.close();
                    ss = null;
                    //阻塞main线程，不再允许接收客户端
                    LockSupport.park();

                    //沉睡时间足够将线程归还到线程池中
                    TimeUnit.MILLISECONDS.sleep(500);

                    //此时有客户端释放，允许继续接收客户端
                    ss = new ServerSocket(8899);
                }
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
